package main

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
	"fmt"
)

type Info struct {
	Status string `json:"status"`
	Addr   string `json:"addr"`
	Age    int    `json:"age"`
}

// Scan 从数据库中读取出来
func (i *Info) Scan(value interface{}) error {
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
	}

	err := json.Unmarshal(bytes, i)
	return err
}

// Value 存入数据库
func (i Info) Value() (driver.Value, error) {
	return json.Marshal(i)
}

type Users struct {
	ID   uint
	Name string
	Info Info `gorm:"type:string"`
}

func main() {
	DB.AutoMigrate(&Users{})
	DB.Create(&Users{
		Name: "xx",
		Info: Info{
			Status: "success",
			Addr:   "xxxx",
			Age:    21,
		},
	})
	var user Users
	DB.Take(&user)
	fmt.Println(user)
}
